package cn.lblbc.webbrowser

import android.animation.ObjectAnimator
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.animation.DecelerateInterpolator
import android.widget.ImageButton
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import cn.lblbc.webbrowser.models.HistoryItem
import cn.lblbc.webbrowser.utils.HistoryManager

class HistoryActivity : BaseActivity() {
    private lateinit var historyRecyclerView: RecyclerView
    private lateinit var historyAdapter: HistoryAdapter
    private lateinit var closeButton: ImageButton
    private lateinit var clearHistoryButton: ImageButton
    private lateinit var emptyStateText: TextView
    private lateinit var historyManager: HistoryManager
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_history)
        
        initViews()
        setupRecyclerView()
        setupListeners()
        loadHistory()
    }
    
    private fun initViews() {
        historyRecyclerView = findViewById(R.id.historyRecyclerView)
        closeButton = findViewById(R.id.closeButton)
        clearHistoryButton = findViewById(R.id.clearHistoryButton)
        emptyStateText = findViewById(R.id.emptyStateText)
        historyManager = HistoryManager(this)
    }
    
    private fun setupRecyclerView() {
        historyRecyclerView.layoutManager = LinearLayoutManager(this)
        
        historyAdapter = HistoryAdapter(
            onHistoryItemClicked = { historyItem ->
                // 返回结果给MainActivity
                val intent = Intent().apply {
                    putExtra("url", historyItem.url)
                }
                setResult(RESULT_OK, intent)
                finish()
            },
            onDeleteClicked = { historyItem ->
                historyManager.deleteHistoryItem(historyItem.url)
                loadHistory()
            },
            formatDate = { timestamp ->
                historyManager.formatDate(timestamp)
            }
        )
        
        historyRecyclerView.adapter = historyAdapter
    }
    
    private fun setupListeners() {
        closeButton.setOnClickListener {
            finish()
        }
        
        clearHistoryButton.setOnClickListener {
            showClearHistoryConfirmation()
        }
    }
    
    private fun showClearHistoryConfirmation() {
        AlertDialog.Builder(this)
            .setTitle(R.string.clear_history)
            .setMessage(R.string.clear_history_confirmation)
            .setPositiveButton(android.R.string.ok) { _, _ ->
                historyManager.clearHistory()
                loadHistory()
                Toast.makeText(this, R.string.history_cleared, Toast.LENGTH_SHORT).show()
            }
            .setNegativeButton(android.R.string.cancel, null)
            .show()
    }
    
    private fun loadHistory() {
        val history = historyManager.getHistory()
        historyAdapter.submitList(history)
        
        if (history.isEmpty()) {
            historyRecyclerView.visibility = View.GONE
            emptyStateText.visibility = View.VISIBLE
        } else {
            historyRecyclerView.visibility = View.VISIBLE
            emptyStateText.visibility = View.GONE
        }
    }
    
    class HistoryAdapter(
        private val onHistoryItemClicked: (HistoryItem) -> Unit,
        private val onDeleteClicked: (HistoryItem) -> Unit,
        private val formatDate: (Long) -> String
    ) : RecyclerView.Adapter<HistoryAdapter.HistoryViewHolder>() {
        
        private var historyItems: List<HistoryItem> = emptyList()
        
        fun submitList(newList: List<HistoryItem>) {
            historyItems = newList
            notifyDataSetChanged()
        }
        
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): HistoryViewHolder {
            val view = LayoutInflater.from(parent.context).inflate(R.layout.item_history, parent, false)
            return HistoryViewHolder(view)
        }
        
        override fun onBindViewHolder(holder: HistoryViewHolder, position: Int) {
            val historyItem = historyItems[position]
            
            holder.historyTitle.text = historyItem.title
            holder.historyUrl.text = historyItem.url
            holder.historyDate.text = formatDate(historyItem.timestamp)
            
            // 添加进入动画
            holder.itemView.alpha = 0f
            holder.itemView.translationY = 50f
            
            val animator = ObjectAnimator.ofFloat(holder.itemView, "alpha", 0f, 1f)
            val translationAnimator = ObjectAnimator.ofFloat(holder.itemView, "translationY", 50f, 0f)
            
            animator.duration = 300
            translationAnimator.duration = 300
            animator.interpolator = DecelerateInterpolator()
            translationAnimator.interpolator = DecelerateInterpolator()
            animator.startDelay = (position * 50).toLong()
            translationAnimator.startDelay = (position * 50).toLong()
            
            animator.start()
            translationAnimator.start()
            
            holder.itemView.setOnClickListener { onHistoryItemClicked(historyItem) }
            holder.deleteButton.setOnClickListener { onDeleteClicked(historyItem) }
        }
        
        override fun getItemCount(): Int = historyItems.size
        
        class HistoryViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
            val historyIcon: ImageView = itemView.findViewById(R.id.historyIcon)
            val historyTitle: TextView = itemView.findViewById(R.id.historyTitle)
            val historyUrl: TextView = itemView.findViewById(R.id.historyUrl)
            val historyDate: TextView = itemView.findViewById(R.id.historyDate)
            val deleteButton: ImageButton = itemView.findViewById(R.id.deleteButton)
        }
    }
}